package com.ltsh.fim.service.context;

import org.beetl.sql.core.*;
import org.beetl.sql.core.db.DBStyle;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.ext.DebugInterceptor;

import java.io.IOException;
import java.util.Properties;

public class ApplicationContext {
    private static Properties properties = new Properties();
    private static SQLManager sqlManager;
    public static void init() {
        try {
            properties.load(ApplicationContext.class.getResourceAsStream("/jdbc.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        initDb();
    }

    private static void initDb() {
        String dbDriver = properties.getProperty("db.driver");
        String dbUrl = properties.getProperty("db.url");
        String dbUserName = properties.getProperty("db.userName");
        String dbPassword = properties.getProperty("db.password");
        ConnectionSource source = ConnectionSourceHelper.getSimple(dbDriver, dbUrl, dbUserName, dbPassword);

        DBStyle mysql = new MySqlStyle();
        // sql语句放在classpagth的/sql 目录下
        String dbSqlFile = properties.getProperty("db.sql.file");
        SQLLoader loader = new ClasspathLoader(dbSqlFile);
        // 数据库命名跟java命名一样，所以采用DefaultNameConversion，还有一个是UnderlinedNameConversion，下划线风格的，
        UnderlinedNameConversion nc = new  UnderlinedNameConversion();
        // 最后，创建一个SQLManager,DebugInterceptor 不是必须的，但可以通过它查看sql执行情况
        sqlManager = new SQLManager(mysql,loader,source,nc,new Interceptor[]{new DebugInterceptor()});
    }

    public static SQLManager getSqlManager() {
        return sqlManager;
    }
}
